package com.xiang.sql.service;

import java.util.ArrayList;
import java.util.List;

import jakarta.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.WebSocket.WebSocketService;
import com.xiang.api.Util;
import com.xiang.sql.entity.User;
import com.xiang.sql.StaticSql;
import com.xiang.sql.entity.Prize;
import com.xiang.sql.entity.PrizeGroup;
import com.xiang.sql.mapper.PrizeMapper;

/**
 * 奖品 服务实现类
 * 
 * @author mac-xiang
 */
@Service
public class PrizeService extends ServiceImpl<PrizeMapper, Prize> {
  @Resource
  PrizeMapper mapper;

  private QueryWrapper<Prize> readWrapper(JSONObject p, User per) {
    QueryWrapper<Prize> ret = Util.getQuery(p, Prize.class);
    if (per != null && !per.per("奖品查询")) {
      ret.select("id,`name`,`image`");
    }
    return ret;
  }

  private List<Prize> getList(JSONObject p, User per) {
    return mapper.selectList(readWrapper(p, per));
  }

  private Page<Prize> getPage(Page<Prize> page, JSONObject p, User per) {
    return mapper.selectPage(page == null ? new Page<Prize>(1, 100) : page, readWrapper(p, per));
  }

  public Prize create(JSONObject p, User per) {
    if (per != null && per.per("奖品创建")) {
      Prize entity = Util.getEntity(p, Prize.class);
      // entity.createTime = null;
      // entity.create = per.id;
      mapper.insert(entity);
      return entity;
    }
    throw new RuntimeException("没有权限");
  }

  public int update(JSONObject p, User per) {
    if (per != null && per.per("奖品修改")) {
      Prize entity = Util.getEntity(p, Prize.class);
      QueryWrapper<Prize> qw = Util.getQuery(p, Prize.class);
      if (this.count(qw) > 10) {
        throw new RuntimeException("单次修改数量超过10条");
      }
      // entity.create = null;
      return mapper.update(entity, qw);
    }
    throw new RuntimeException("没有权限");
  }

  public Object read(JSONObject p, User per) {
    Page<Prize> page = Util.getPage(p, Prize.class);
    return page == null ? getList(p, per) : getPage(page, p, per);
  }

  public int delete(JSONObject p, User per) {
    if (per != null && per.per("奖品删除")) {
      QueryWrapper<Prize> q = Util.getQuery(p, Prize.class);
      if (this.count(q) > 10) {
        throw new RuntimeException("删除数据的数量不能超过10条");
      }
      return mapper.delete(q);
    }
    throw new RuntimeException("没有权限");
  }

  public long count(JSONObject p, User per) {
    return this.count(readWrapper(p, per));
  }

  @Autowired
  WebSocketService ws;

  public Object lottery(JSONObject p, User per) {
    Util.clear();
    String id = p.getString("id");
    if (id == null) {
      throw new RuntimeException("请从正确页面进入");
    }
    PrizeGroup prizeGroup = StaticSql.service.prizeGroup.getById(id);
    if (prizeGroup == null) {
      throw new RuntimeException("非法进入");
    }
    if (prizeGroup.useTime > 0) {
      if (!prizeGroup.user.equals(per.id)) {
        throw new RuntimeException("二维码已被使用");
      }
      // ws.sendTarget("二次扫码已固化", per.id);
    }
    QueryWrapper<Prize> qw = new QueryWrapper<>();
    qw.in("id", prizeGroup.content);
    List<Prize> list = mapper.selectList(qw);
    int s = 0, t = 0;
    for (Prize e : list) {
      t = e.sum * e.weight;
      e.sum = s;
      s += t;
      e.weight = s;
    }
    Prize item = null;
    if (prizeGroup.prize != null && prizeGroup.prize.length() > 0) {
      item = this.getById(prizeGroup.prize);
    }
    while (item == null) {
      int a = Util.rand(s);
      item = Util.arrFind(list, e -> {
        return e.sum < a && a <= e.weight;
      });
    }
    for (Prize e : list) {
      e.sum = e.id.equals(item.id) ? 1 : null;
      e.weight = null;
    }
    if (prizeGroup.useTime.equals(0L)) {
      List<String> sql = new ArrayList<>();
      sql.add("START TRANSACTION;");
      sql.add(String.format("UPDATE `prize` SET `sum`=`sum`-1 WHERE (id = '%s');", item.id));
      sql.add(String.format("UPDATE `prize_group` SET `user`='%s', `use_time`='%s', `prize`='%s' WHERE (id = '%s');",
          per.id, Util.time(), item.id, prizeGroup.id));
      if (item.value.indexOf("money:") == 0) {
        StaticSql.service.transfer.transferPrize(prizeGroup, item);
      } else if (item.value.indexOf("goods:") == 0) {
        // StaticSql.service.order.prizeGoods(per, item.value.substring(6),
        //     String.format("中奖:%s-%s", item.id, item.name));
      }
      // sql.add(String.format("UPDATE `order` SET `prize`='%s' WHERE (id = '%s');",
      // item.id, oid));

      sql.add("COMMIT;");
      try {
        StaticSql.run.select(String.join("\n", sql));
      } catch (Exception e) {
        throw new RuntimeException("抽奖服务器出错,请稍后尝试");
      }
    }
    return list;
  }
}
